import { ref } from 'vue'

export class DialogQueue {
  constructor() {
    this.queue = ref([])
    this.isVisible = ref(false)
  }

  /**
   * 显示对话框
   * @param {Object} dialog - 对话框配置
   * @param {Function} dialog.onLoaded - 对话框加载完成回调
   * @param {Function} dialog.onHidden - 对话框隐藏回调
   * @returns {Promise} 对话框关闭时resolve
   */
  show(dialog) {
    return new Promise((resolve) => {
      const dialogWithResolve = {
        ...dialog,
        resolve
      }

      this.queue.value.push(dialogWithResolve)

      // 如果当前没有显示的对话框，显示下一个
      if (!this.isVisible.value) {
        this.showNextDialog()
      }
    })
  }

  showNextDialog() {
    if (this.queue.value.length === 0) {
      return
    }

    const dialog = this.queue.value[0]
    this.isVisible.value = true

    // 调用加载回调
    if (dialog.onLoaded) {
      dialog.onLoaded()
    }
  }

  /**
   * 隐藏当前对话框
   * @param {*} result - 对话框的结果值
   */
  hide(result) {
    if (this.queue.value.length === 0 || !this.isVisible.value) {
      return
    }

    this.isVisible.value = false
    const dialog = this.queue.value.shift()
    
    // 调用隐藏回调
    if (dialog.onHidden) {
      dialog.onHidden()
    }

    // 添加一个适当的延迟，显示动画
    setTimeout(() => {
      dialog.resolve(result)
      this.showNextDialog()
    }, 100)
  }

  /**
   * 获取当前队列长度
   * @returns {number} 队列长度
   */
  getQueueLength() {
    return this.queue.value.length
  }

  /**
   * 清空队列
   */
  clearQueue() {
    this.queue.value = []
    this.isVisible.value = false
  }
}